﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using System.Text;
using Newtonsoft.Json;

namespace PeisongWeb.admin
{
    public partial class sennightOrderEdit : adminPage
    {
        #region Part 1
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("DJ", 2))
                {
                    drpCompanyBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        /// <summary>
        /// 绑定所有采购商
        /// </summary>

        private void drpCompanyBind()
        {
            //DataTable dt = logic.company.listWithWeeklyPrice();
            DataTable dt = logic.company.listWithCompanyType("2");
            drp_company.DataSource = dt;
            drp_company.DataBind();
            drp_company.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            //ext_receiveDt.SelectedDate = DateTime.Now;
        }

        protected void lbn_AddProduct_Click(object sender, EventArgs e)
        {
            categoryRootBind();
            categorySubBind();
            rptProBind();
            win_product.Show();
        }

        protected void drp_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            hd_proScope.Value = "";
            if (drp_company.SelectedValue.Trim() != "")
            {
                DataSet ds = logic.company.select("companyid=" + drp_company.SelectedValue.Trim(), "companyid", 1, 1);
                DataRow dr = ds.Tables[1].Rows[0];
                lbl_contact.Text = dr["contact"].ToString();
                lbl_Address.Text = dr["area"].ToString() + dr["address"].ToString();
                lbl_contactMobile.Text = dr["mobile"].ToString();
                lbl_contactPhone.Text = dr["Phone"].ToString();
            }
            else
            {
                lbl_contact.Text = "请选择公司";
                lbl_Address.Text = "请选择公司";
                lbl_contactMobile.Text = "请选择公司";
                lbl_contactPhone.Text = "";
            }
        }

        #endregion

        #region Part 2
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        /// <summary>
        /// 绑定在采购商的采购范围里的所有商品
        /// </summary>
        void rptProBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("isSale=1");

            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat("and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo like '%{0}%'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] like '%{0}%'", txt_ProductName.Text.Trim());

            //DataSet ds = logic.product.select(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            DataSet ds = logic.sellerRange.snnightOrderOptimize(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);

            //DataTable dt_seller = logic.sellerRange.list();
            ViewState["seller"] = ds.Tables[2];

            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();

        }

        protected void rpt_Products_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DropDownList ddl = e.Item.FindControl("ddl") as DropDownList;
                DataRowView dv = e.Item.DataItem as DataRowView;

                DataTable dt = ViewState["seller"] as DataTable;
                DataView view = new DataView(dt);
                view.RowFilter = string.Format("productId={0}", dv["productId"]);
                view.Sort = "coi DESC";

                ddl.DataSource = view;
                ddl.DataBind();
            }
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }

        void categoryRootBind()
        {
            //当采购商不等于空的时候，绑定在采购商的采购范围的大类
            if (drp_company.SelectedValue != "")
            {
                int companyId = Convert.ToInt32(drp_company.SelectedValue);
                //ddl_CategoryRoot.DataSource = logic.category.listWithCompanyRange(companyId);
                ddl_CategoryRoot.DataSource = logic.category.getByParent(0);
                ddl_CategoryRoot.DataBind();
                ddl_CategoryRoot.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            }
            else
            {
                ddl_CategoryRoot.Items.Clear();
            }
        }

        void categorySubBind()
        {
            //当大类不等于空的时候，就绑定小类
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
            }
            else
            {
                ddl_CategorySub.Items.Clear();
            }
        }

        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        protected void ddl_CategorySub_SelectedIndexChanged(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        #endregion

        /// <summary>
        /// 提交周价订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            // 日志记录
            log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
            logger.Info("周价订单信息:" + hd_proScope.Value);

            // 订单细目
            List<OrderItemEntity> orderItems = JsonConvert.DeserializeObject<List<OrderItemEntity>>(hd_proScope.Value);

            if (orderItems.Count > 0)
            {
                // 计算订单总价
                decimal serverTotalAmount = 0m;
                orderItems.ForEach(x => serverTotalAmount += x.Quantity * x.Price);
                serverTotalAmount = Math.Round(serverTotalAmount,2, MidpointRounding.AwayFromZero);

                decimal clientHotalAmount = 0m;
                decimal.TryParse(hd_TotalAmount.Value, out clientHotalAmount);

                int companyid = Convert.ToInt32(drp_company.SelectedValue);
                OrderEntity od = new OrderEntity();
                od.Amount = serverTotalAmount;
                od.CompanyId = companyid;
                od.StandardAmount = od.Amount;
                od.CustomerId = logic.sysAdmin.AdminID;
                od.FireightFee = Convert.ToDecimal(txt_fireightFee.Value);
                od.Note = txt_Note.Text;
                od.OrderNo = "";
                od.Source = "4";    //订单来源：1、网站订单；2、电话订单；3.补单；4、周价补单
                od.Taxfee = Convert.ToDecimal(txt_taxfee.Value);
                od.Status = "1";
                od.ReceiveDt = Convert.ToDateTime(DateTime.Now.AddDays(1).ToShortDateString()).AddHours(Convert.ToInt32(ddl_receiveTime.SelectedValue));

                od.TypeCount = orderItems.Count;
                int orderid = logic.order.insert(od);

                // businessNature
                string businessNature = logic.company.getById(companyid).BusinessNature;

                foreach (OrderItemEntity orderItem in orderItems)
                {
                    orderItem.CustomerId = logic.sysAdmin.AdminID;
                    orderItem.OrderId = orderid;
                    orderItem.InitQuantity = orderItem.Quantity;
                    orderItem.BusinessNature = businessNature;
                    logic.orderItem.insert(orderItem);
                }

                Library.Script.ClientMsgUrl("订单保存成功!", "sennightOrderList.aspx");
            }
            else
            {
                Library.Script.ClientMsg("订单数据无效！");
                return;
            }
        }

    }
}
